<template>
  <!-- 弹窗 -->
  <el-dialog v-model="dialogVisible" v-if="dialogVisible" :show-close="false" :title="title"
    :close-on-click-modal="false" width="25%">
    <el-card>
      <el-form ref="ruleFormRef" style="max-width: 300px" :model="ruleForm" status-icon :rules="rules"
        label-width="auto" class="demo-ruleForm">
        <el-form-item label="药品"  prop="name">
          <el-input v-model="ruleForm.name"  placeholder="请输入药品名称"/>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select clearable v-model="value" placeholder="请选择分类" style="width: 120px">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格/元" prop="price">
          <el-input v-model="ruleForm.price" placeholder="请输入价格" />
        </el-form-item>
    

        <el-form-item label="图片" prop="image">
          <Upload ref="upload" :oldImage="oldImage"></Upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="ruleForm.description" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">起售</el-radio>
            <el-radio :label="0">禁售</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="margin-left: 100px;">
          <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
          <el-button type="primary" @click="cancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-dialog>
</template>

<script lang="ts" setup>
import Upload from '../../components/Upload.vue'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

//分类选择框
const categoryList = ref([])
const value = ref()


// 获取分类列表
import { getCategories } from '@/apis/category.js'
async function getCategoryList() {
  const res = await getCategories(1)
  console.log(res.data.data)
  categoryList.value = res.data.data
}
getCategoryList()

const upload = ref()
const props = defineProps({
  onSubmit: Function
})
const dialogVisible = ref(false)
const isadd = ref()
const title = ref('')
function changeDialogVisible(val: boolean) {
  if (val === true) {
    title.value = "新增药品"
  }
  if (val === false) {
    title.value = "修改药品"
  }
  dialogVisible.value = true
  isadd.value = val;
}
const oldImage = ref('')
import { nextTick } from 'vue';
function editFormData(row: any) {
  oldImage.value = row.image
  nextTick(() => {
    ruleForm.id = row.id
    ruleForm.name = row.name
    value.value = row.categoryId
    ruleForm.price = row.price
    ruleForm.image = row.image
    ruleForm.description = row.description
    ruleForm.status = row.status
  })

}
defineExpose({
  changeDialogVisible,
  editFormData
})
//表单
const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
  id: null,
  name: '',
  categoryId: null,
  price: null,
  image: '',
  description: '',
  status: null,
})

const checkPrice = (rule: any, value: any, callback: any) => {
  if (value === null || value === '') {
    callback(new Error('请输入价格!'))
  } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
    callback(new Error("菜品价格格式有误，请输入大于零且最多保留两位小数的金额!"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof ruleForm>>({
  name: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类!', trigger: 'blur' }],
  price: [{ required:true,validator: checkPrice, trigger: 'blur' },],
  image: [{ required: true, message: '请添加图片!', trigger: 'blur' }],
  status: [{ required: true, message: '请设置状态!', trigger: 'blur' }],
})
import { addDish } from '@/apis/dish'
import { ElMessage } from 'element-plus'

import { updateDish } from '@/apis/dish.js'
const submitForm = (formEl: FormInstance | undefined) => {
  ruleForm.image = upload.value.imageUrl
  console.log(upload.value.imageUrl);
  ruleForm.categoryId = value.value
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (isadd.value === true) {
        //提交添加请求
        const res = await addDish(ruleForm)
        console.log(res.data.code);
        if (res.data.code === 0) {
          ElMessage.error(res.data.msg)
          return
        }
        resetForm(formEl)
        ElMessage.success("添加成功")
        oldImage.value = ''
        value.value = null
        dialogVisible.value = false

        //刷新表格
        props.onSubmit()

        console.log('submit!')
      } else {
        //提交 修改请求
        const res = await updateDish(ruleForm)
        console.log(res.data.code);
        if (res.data.code === 0) {
          ElMessage.error(res.data.msg)
          return
        }
        resetForm(formEl)
        ElMessage.success("修改成功")
        oldImage.value = ''
        value.value = null
        dialogVisible.value = false
        //刷新表格
        props.onSubmit()
        console.log('submit!')
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
function cancel() {
  resetForm(ruleFormRef.value)
  oldImage.value = ''
  value.value = null
  dialogVisible.value = false
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>